const app = getApp();
const MMPDB = wx.cloud.database();
const graph = MMPDB.collection('articles');
const _ = MMPDB.command
Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    canIUse: wx.canIUse('button.open-type.getuserinfo'),
    hasUserInfo: false,
    userInfo: null,
    isGenerate: false,
    isSweep:false,

    modalName: '',
    comment: '',
    detailsObj: '',
    cardInfo: {
      banner: "cloud://laozhongyi-f1f28d.6c61-laozhongyi-f1f28d/share.png",
      TagText: "", //标签
      text1: "识别小程序二维码，进入", //职位
      appName: "养生老中医", //手机
      text2: "查看新闻", //公司
    },
  },
  pengyouquanBtn: function() {
    var that = this;
    that.setData({
      modalName: "Modal"
    })
    if (!that.data.isGenerate) {
      that.loadBanner();
    } else {
      that.saveShareImg();
    }

    
  },
  pengyouBnt: function(e) {
    this.onShareAppMessage();

  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  backTap: function() {
    wx.navigateBack();
  },
  lastBtn: function(e) {
    wx.navigateBack({
      delta: 1
    })
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
    this.pengyouquanBtn();
  },
  /**
   * 先下载头像图片
   */
  loadBanner: function() {
    var that = this;

    wx.cloud.downloadFile({
      fileID: that.data.cardInfo.banner,
      success: res => {
        that.loadERCode(res.tempFilePath);
      },
      fail: err => {
        // handle error
        console.log(err)
      }
    })
  },

  /**
   * 下载二维码图片
   */
  loadERCode: function(avaterSrc) {

    wx.showLoading({
      title: '生成中...',
      mask: true,
    });
    var that = this;
    wx.cloud.callFunction({
      name: 'getToken',
      data: {
        id: that.data.detailsObj._id,
        page: "pages/articleList/intro/index"
      },
      complete: res => {
        wx.cloud.downloadFile({
          fileID: res.result.tempFilePath,
          success: res => {
            that.sharePosteCanvas(avaterSrc, res.tempFilePath);
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      fail: err => {
        console.log(err)
        wx.hideLoading();
      }
    })


  },

  /**
   * 开始用canvas绘制分享海报
   * @param avaterSrc 下载的头像图片路径
   * @param codeSrc   下载的二维码图片路径
   */
  sharePosteCanvas: function(avaterSrc, codeSrc) {
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })

    var that = this;
    var cardInfo = that.data.cardInfo; //需要绘制的数据集合
    const ctx = wx.createCanvasContext('myCanvas'); //创建画布
    var width = "";
    wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function(rect) {
      var height = rect.height;
      var right = rect.right;
      width = rect.width;
      var left = rect.left;
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, rect.width, height);

      //头像为正方形
      if (avaterSrc) {
        ctx.drawImage(avaterSrc, 0, 0, rect.width, 383 / 2.5);
        ctx.setFontSize(14);
        ctx.setFillStyle('#fff');
        ctx.setTextAlign('left');
      }
      cardInfo.TagText = that.data.detailsObj.title;
      //标题
      if (cardInfo.TagText) {

        const CONTENT_ROW_LENGTH = 21; // 正文 单行显示字符长度
        let [contentLeng, contentArray, contentRows] = that.textByteLength(cardInfo.TagText.replace(/\s+/g, ""), CONTENT_ROW_LENGTH);
        ctx.setTextAlign('left');
        ctx.setFillStyle('#000');
        ctx.setFontSize(30);
        let contentHh = 30 * 1;
        for (let m = 0; m < contentArray.length; m++) {
          ctx.fillText(contentArray[m], left, width - 120 + contentHh * m);
        }
      }

      //姓名
      if (that.data.userInfo.nickName) {
        ctx.setFontSize(14);
        ctx.setFillStyle('#000');
        ctx.setTextAlign('left');
        ctx.fillText(that.data.userInfo.nickName, left + 100, width - 20);
      }
      if (that.data.userInfo.nickName) {
        ctx.setFontSize(14);
        ctx.setFillStyle('#666');
        ctx.setTextAlign('left');
        ctx.fillText("正在读这篇文章", left + 190, width - 20);
      }
      //名称
      if (cardInfo.text1) {
        ctx.setFontSize(12);
        ctx.setFillStyle('#666');
        ctx.setTextAlign('left');
        ctx.fillText(cardInfo.text1, left + 100, width + 10);
      }
      if (cardInfo.appName) {
        ctx.setFontSize(12);
        ctx.setFillStyle('#0066ff');
        ctx.setTextAlign('left');
        ctx.fillText(cardInfo.appName, left + 100, width + 30);
      }
      if (cardInfo.text2) {
        ctx.setFontSize(12);
        ctx.setFillStyle('#666');
        ctx.setTextAlign('left');
        ctx.fillText(cardInfo.text2, left + 170, width + 30);
      }
      //  绘制二维码
      if (codeSrc) {
        ctx.drawImage(codeSrc, left, width - 40, width / 4, width / 4)
      }

    }).exec()

    setTimeout(function() {
      ctx.draw();
      that.setData({
        isGenerate: true
      })
      wx.hideLoading();
      that.saveShareImg();
    }, 1000)

  },

  /**
   * 多行文字处理，每行显示数量
   * @param text 为传入的文本
   * @param num  为单行显示的字节长度
   */
  textByteLength(text, num) {
    let strLength = 0; // text byte length
    let rows = 1;
    let str = 0;
    let arr = [];
    for (let j = 0; j < text.length; j++) {
      if (text.charCodeAt(j) > 255) {
        strLength += 2;
        if (strLength > rows * num) {
          strLength++;
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      } else {
        strLength++;
        if (strLength > rows * num) {
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      }
    }
    arr.push(text.slice(str, text.length));
    return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
  },

  //点击保存到相册
  saveShareImg: function() {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function() {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function(res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {

              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function(res) {
                  if (res.confirm) {}
                },
                fail: function(res) {}
              })
            },
            fail: function(res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },

  // 指定方式
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(op) {
    var that = this;


    var c = that.initChart;
    that.setData({
      ec: {
        onInit: c
      }
    })
    if (op.scene) {
      const scene = decodeURIComponent(op.scene);
      op.id = scene.split("=")[1];
      that.setData({ isSweep: true});
    }
    graph.where({
      _id: op.id
    }).get().then(res => {



      that.onCounterDec(op.id);
      that.setData({
        detailsObj: res.data[0],
        spinShow: false
      });
    })
    if (app.globalData.userInfo) {
      that.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (that.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        that.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          that.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  recordDec: function() {

    const updata = ercode.add({
      data: data
    });

  },
  onCounterDec: function(id) {
    wx.cloud.callFunction({
      name: 'counterDec',
      data: {
        id: id
      },
      complete: res => {

        console.log(res)
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})